const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: '',
    // false,非新人，无授权按钮
    // true,新人，有授权按钮
    isNew: false,
    cid: '',
    avatarUrl:'',
  },

  getUserProfile(e) {
    var that = this
    wx.getUserProfile({
      desc: '用于获取用户头像', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        if (res.userInfo != null) {
          wx.setStorageSync('avatarInfo', res.userInfo)
          app.globalData.userInfo = res.userInfo
          wx.login({
            success: res => {
              var code = res.code
              new Promise(async (resolve, reject) => {
                await wx.User.login({
                  url: "/auth/login",
                  data: {
                    code: code,
                    userAvatar: wx.getStorageSync('avatarInfo').avatarUrl,
                    userAlias:wx.getStorageSync('avatarInfo').nickName
                  }
                })
                resolve(wx.getStorageSync('userinfo').type)
              }).then(res => {
                that.setData({
                  avatarUrl: wx.getStorageSync('avatarInfo').avatarUrl,
                  nickName: wx.getStorageSync('userinfo').name
                })
                var cid = this.data.cid
                var data = {
                  uid: wx.getStorageSync('userinfo').uid,
                  cid: cid
                }
                wx.User.joinClass({
                  url: "/class/joinClass",
                  data: data
                })
                setTimeout(
                  function () {
                    wx.redirectTo({
                      url: '../guide/guide',
                    })
                  },
                  1500)
              })
            }
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      cid: options.cid
    })
    var that = this

    // 新用户或者未登录用户(清除过缓存的用户)
    if (wx.getStorageSync('userinfo').uid == null || wx.getStorageSync('userinfo') == '') {
      // 新用户
      // 登录
      this.setData({
        isNew: true,
      })
    } else {
      // 已经登陆过的用户
      this.setData({
        avatarUrl:wx.getStorageSync('userinfo').avatar
      })
      var data = {
        uid: wx.getStorageSync('userinfo').uid,
        cid: this.data.cid
      }
      wx.User.joinClass({
        url: "/class/joinClass",
        data: data
      })
    }
  },
})